<?php
/**
 * Created by PhpStorm.
 * User: neilchen
 * Date: 2017/5/16
 * Time: 14:33
 */

namespace api\modules\v1\controllers;

use common\business\EhrHelper;
use common\business\kd\LoginApiHandler;
use common\business\upload\UploadHelper;
use common\consts\MdmConsts;
use common\helpers\StringUtil;
use common\models\kingdee\HrPersonPhoto;
use common\models\kingdee\Person;
use common\models\kingdee\PmUser;
use common\models\ResponseData;
use common\models\StatusCodeEnum;
use common\models\User;
use Yii;
use api\models\LoginForm;
use yii\filters\auth\QueryParamAuth;
use yii\filters\RateLimiter;
use yii\helpers\ArrayHelper;
use yii\helpers\Json;
use yii\helpers\Url;
use yii\rest\ActiveController;
use yii\web\BadRequestHttpException;
use yii\web\GoneHttpException;
use yii\web\IdentityInterface;
use yii\web\Response;
use common\consts\Consts;

class UsersController extends ActiveController
{
    public $modelClass = 'common\models\User';

    public function behaviors()
    {
        return ArrayHelper::merge (parent::behaviors(), [
            'authenticator' => [
                'class' => QueryParamAuth::className(),
                'optional' => [
                    'rest-login',
                    'login',
                    'user-profile',
                    'current',
                ],
            ],
        ] );
    }

//    public function behaviors() {
//        $behaviors = parent::behaviors();
//
//        $behaviors['rateLimiter'] = [
//            'class' => RateLimiter::className(),
//            'enableRateLimitHeaders' => true,
//        ];
//
////        是否要验证
////        $behaviors['authenticator'] = [
////            'class' => CompositeAuth::className(),
////            'authMethods' => [
////                /*下面是三种验证access_token方式*/
////                //1.HTTP 基本认证: access token 当作用户名发送，应用在access token可安全存在API使用端的场景，例如，API使用端是运行在一台服务器上的程序。
////                //HttpBasicAuth::className(),
////                //2.OAuth 2: 使用者从认证服务器上获取基于OAuth2协议的access token，然后通过 HTTP Bearer Tokens 发送到API 服务器。
////                //HttpBearerAuth::className(),
////                //3.请求参数: access token 当作API URL请求参数发送，这种方式应主要用于JSONP请求，因为它不能使用HTTP头来发送access token
////                //http://localhost/user/index/index?access-token=123
////                QueryParamAuth::className(),
////            ],
////        ];
//
////        $behaviors['contentNegotiator']['formats']['text/html'] = Response::FORMAT_JSON;
//        return $behaviors;
//    }

    public function actionRestLogin(){
        $request_body = file_get_contents('php://input');
        $data = json_decode($request_body, true);

        $model = new LoginForm([
            'username' => $data['userName'],
            'password' => $data['password'],
        ]);

        $userName = $data['userName'];
        $password = $data['password'];

        $api = new LoginApiHandler();
        $resultStr = $api->webServiceCallSync($userName, $password);
        $resultArr = Json::decode($resultStr);

        $avatar = null;
        if ($resultArr[MdmConsts::RESULT] == Consts::YES){
            $userInDb = User::findOne(['username' => $userName]);
            if (!$userInDb){
                $userInDb = new User();
                $userInDb->username = $userName;
                $userInDb->email = sprintf('%s@stec.com', $userName);
                $userInDb->auth_key = $password;
                $userInDb->password_hash = md5($password);
                $userInDb->access_token = $resultArr['sessionId'];
                $userInDb->created_at = time();
                $userInDb->updated_at = $userInDb->created_at;
                $userInDb->save();
            }

            $userInDb = User::findOne(['username' => $userName]);

            $kdUser = PmUser::findOne(['FNUMBER' => $userName]);
            //先在SHR系统中匹配用户
            if ($kdUser){
                $userInDb->fullname = $kdUser->FNAME_L2;
                $userInDb->email = $kdUser->FEMAIL;
                $userInDb->access_token = $resultArr['sessionId'];
                $userInDb->updated_at = time();

                $personPhoto = HrPersonPhoto::findOne([
                    'FPERSONID' => $kdUser->FPERSONID,
                ]);
                $person = Person::findOne(['FID' => $kdUser->FPERSONID]);

                if ($person){
                    $positionName = EhrHelper::getPersonPosition($person->FID);
                    $userInDb->position = $positionName;

                    $imageName = $person->FGENDER == Consts::GENDER_MALE ? 'male_unknown.jpg' : 'female_unknown.jpg';
                    $userInDb->avatar = Url::to("@web/images/$imageName");

                    if ($personPhoto){
                        $filePath = Yii::getAlias('@api/web/images/employee_photos/');
                        $fileExtArr = explode('/', $personPhoto->FIMAGECONTENTTYPE);
                        $fileName = sprintf('%s.%s', $person->FNUMBER, $fileExtArr[1]);

                        $imageData = stream_get_contents($personPhoto->FIMAGEDATA);
                        $uploadResult = UploadHelper::uploadFile($filePath, $fileName, $imageData);

                        if ($uploadResult->isSuccess){
                            $userInDb->avatar = Url::to("@web/images/employee_photos/$fileName");
                        }
                    }
                }
                else {
                    $userInDb->avatar = Url::to("@web/images/male_unknown.jpg");
                }

                if (StringUtil::isNullOrWhiteSpace($userInDb->email)){
                    $userInDb->email = sprintf('%s@stec.com', $userInDb->username);
                }
                $userInDb->save();
            }

            $returnVal = [
                'currentAuthority' => 'normal',
                'status' => Consts::OK,
                'type' => 'account',
                'accessToken' => $resultArr['sessionId'],
            ];
        }
        else {
            $returnVal = [
                'currentAuthority' => '',
                'status' => Consts::ERROR,
                'type' => 'account',
                'accessToken' => '',
            ];
        }
        return $returnVal;

//        if ($user = $model->login()) {
//            if ($user instanceof IdentityInterface) {
//                $returnVal = [
//                    'currentAuthority' => $user->username,
//                    'status' => Consts::OK,
//                    'type' => 'account',
//                    'accessToken' => $user->access_token,
//                ];
//                return $returnVal;
////                return $user->access_token;
//            } else {
////                return $user->errors;
//                $returnVal = [
//                    'currentAuthority' => $user->username,
//                    'status' => Consts::ERROR,
//                    'type' => 'account',
//                    'accessToken' => '',
//                    'errors' => $user->errors,
//                ];
//                return $returnVal;
//            }
//        } else {
////            return $model->errors;
//            $returnVal = [
//                'currentAuthority' => $model->username,
//                'status' => Consts::ERROR,
//                'type' => 'account',
//                'accessToken' => '',
//                'errors' => $model->errors,
//            ];
//            return $returnVal;
//        }
    }

    /**
     * 登录
     */
    public function actionLogin()
    {
        $model = new LoginForm();
        $model->setAttributes(Yii::$app->request->post());

        if ($user = $model->login()) {
            if ($user instanceof IdentityInterface) {
                $returnVal = [
                    'currentAuthority' => $user->username,
                    'status' => Consts::OK,
                    'type' => 'account',
                    'accessToken' => $user->access_token,
                ];
                return $returnVal;
//                return $user->access_token;
            } else {
//                return $user->errors;
                $returnVal = [
                    'currentAuthority' => $user->username,
                    'status' => Consts::ERROR,
                    'type' => 'account',
                    'accessToken' => '',
                    'errors' => $user->errors,
                ];
                return $returnVal;
            }
        } else {
//            return $model->errors;
            $returnVal = [
                'currentAuthority' => $model->username,
                'status' => Consts::ERROR,
                'type' => 'account',
                'accessToken' => '',
                'errors' => $model->errors,
            ];
            return $returnVal;
        }
    }

    /**
     * 获取用户信息
     */
    public function actionUserProfile ($token)
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        // 到这一步，token都认为是有效的了
        // 下面只需要实现业务逻辑即可，下面仅仅作为案例，比如你可能需要关联其他表获取用户信息等等
        try {
            $user = User::findIdentityByAccessToken($token);
            $resultData = [
                'id' => $user->id,
                'username' => $user->username,
                'email' => $user->email,
            ];
            $responseData = new ResponseData(StatusCodeEnum::SUCCESS, $resultData, null, null);
        } catch (\Exception $e) {
            $responseData = new ResponseData($e->getCode(), null, $e->getMessage(), $e);
        }

        return $responseData->getResultArray();
    }

    public function actionCurrent($access_token = null){
//        if (StringUtil::isNullOrWhiteSpace($access_token)){
//            return [
//                'name' => '',
//                'avatar' => '',
//                'position' => '',
//                'userid'=> '',
//                'notifyCount' => 0,
//            ];
//        }
        $user = User::findOne([
            'access_token' => $access_token,
        ]);
        if (!$user){
            return [
                'name' => '',
                'avatar' => '',
                'position' => '',
                'userid'=> '',
                'notifyCount' => 0,
            ];
        }
        return [
            'name' => $user->username,
            'avatar' => $user->avatar,
            'position' => $user->position,
            'userid'=> $user->id,
            'notifyCount' => 0,
        ];
    }
}